package com.qm.console.component.thirdapi.oss;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.DeleteObjectsResult;
import com.aliyun.oss.model.PolicyConditions;
import com.qm.console.component.exception.BusinessException;
import com.qm.console.component.thirdapi.oss.config.UploadConfig;
import com.qm.console.controller.dto.ResultEnum;
import com.qm.console.component.exception.BusinessException;
import com.qm.console.component.thirdapi.oss.config.UploadConfig;
import com.qm.console.controller.dto.ResultEnum;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class AliYunOSSUtil {

    private static Logger LOG = LoggerFactory.getLogger(AliYunOSSUtil.class);

    public static Map<String, String> getToken(String type) {
        String bucket = null;
        if(type.equals(UploadConfig.file)){
            bucket = UploadConfig.fileBucket;
        }
        else if (type.equals(UploadConfig.image)){
            bucket = UploadConfig.pictureBucket;
        }
        OSS ossClient = new OSSClientBuilder().build(UploadConfig.endPoint, Objects.requireNonNull(UploadConfig.accessKey), Objects.requireNonNull(UploadConfig.secretKey));
        try {
            long expireEndTime = System.currentTimeMillis() + UploadConfig.expireInterval;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConditions = new PolicyConditions();
            policyConditions.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            String postPolicy = ossClient.generatePostPolicy(expiration, policyConditions);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);
            String host = "https://" + bucket + "." + UploadConfig.endPoint;
            Map<String, String> respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", UploadConfig.accessKey);
            respMap.put("host", host);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            JSONObject jasonCallback = new JSONObject();
            jasonCallback.put("callbackUrl", UploadConfig.callbackUrl);
            jasonCallback.put("callbackBody",
                    "filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}");
            jasonCallback.put("callbackBodyType", "application/x-www-form-urlencoded");
            String base64CallbackBody = BinaryUtil.toBase64String(jasonCallback.toString().getBytes());
            respMap.put("callback", base64CallbackBody);
            return respMap;
        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
            throw new BusinessException(ResultEnum.THIRD_OSS_GET_TOKEN_ERROR);
        }
    }

    public static void deleteObject(String key){
        OSS ossClient = new OSSClientBuilder().build(UploadConfig.endPoint, Objects.requireNonNull(UploadConfig.accessKey), Objects.requireNonNull(UploadConfig.secretKey));
        ossClient.deleteObject(UploadConfig.pictureBucket, key);
    }
    public static void deleteObjectList(List<String> keyList){
        LOG.info("keyList: " + keyList);
        OSS ossClient = new OSSClientBuilder().build(UploadConfig.endPoint, Objects.requireNonNull(UploadConfig.accessKey), Objects.requireNonNull(UploadConfig.secretKey));
        DeleteObjectsResult deleteObjectsResult = ossClient.deleteObjects(new DeleteObjectsRequest(UploadConfig.pictureBucket).withKeys(keyList));
        List<String> deletedObjects = deleteObjectsResult.getDeletedObjects();
        LOG.info("deletedObjects: " + deletedObjects);
        ossClient.shutdown();
    }

    public static void main(String[] args) {
        AliYunOSSUtil a = new AliYunOSSUtil();
        System.out.println(a.getToken("image"));
    }

}
